package com.h2cloud.JUCTest.Semaphore;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @Package: com.h2cloud.JUCTest.Semaphore
 * @ClassName: SemaphoreTest
 * @Author: h2cloud
 * @CreateTime: 2022/6/6 3:08 下午
 * @Description:
 */
@Slf4j
public class SemaphoreTest {
    public static void main(String[] args) throws Exception {
        test0();
//        test1();
    }

    public static void test0() {
        // 1. 创建一个对象
        Semaphore semaphore = new Semaphore(3);

        // 2. 开 10 个线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 获取一个许可
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    log.info("start ...");
                    Thread.sleep(1000);
                    log.info("end ....");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "t" + (i + 1)).start();
        }
    }

    // semaphore 初始化有1个令牌，1个线程调用一次 acquire方法，然后调用两次 release方法，
    // 之后另外一个线程调用 acquire(2) 方法，此线程能够获取到足够的令牌并继续运行吗?
    public static void test1() throws Exception {
        Semaphore semaphore = new Semaphore(1);
        semaphore.acquire();
        semaphore.release();
        semaphore.release();

        new Thread(() -> {
            // 获取一个许可
            try {
                semaphore.acquire(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t1 start .. ");
        }, "t1").start();

        Thread.sleep(200000);
    }

}
